package com.sheepone.distributor;

import com.lmax.disruptor.EventHandler;
import com.sheepone.distributor.config.WorkerStationConfig;
import com.sheepone.distributor.event.DistributeEvent;
import com.sheepone.distributor.thread.LoadExecutorHolder;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Miss.杨
 * @description
 * @since 2023-12-07 22:18
 */
public enum WorkerStationManager implements EventHandler<DistributeEvent> {
    INSTANCE;

    private final Map<String, WorkerStation> workerStations = new HashMap<>();
    private final Map<String, LoadExecutorHolder> threadPools = new HashMap<>();

    public void registerWorkerStation(List<WorkerStationConfig> workerLineConfigs) {
        // 注册新增的WorkerStation
        workerLineConfigs.forEach(config -> workerStations.put(config.getStation(), new WorkerStation(config)));
    }

    public void registerThreadPool(String station, LoadExecutorHolder threadPool) {
        threadPools.put(station, threadPool);
    }

    public WorkerStation getWorkerStation(String name) {
        return workerStations.get(name);
    }

    public void stopAll() {
        workerStations.forEach((k, v) -> v.stop());
        threadPools.forEach((k, v) -> v.shotDown());
    }

    public Map<String, WorkerStation> getWorkerStations() {
        return workerStations;
    }

    @Override
    public void onEvent(DistributeEvent event, long l, boolean b) throws Exception {
        WorkerStation workerStation = getWorkerStation(event.getTargetStation());
        while (workerStation.isResizing()) {
            Thread.onSpinWait();
        }
        workerStation.publish((e, s) -> {
            e.setContext(event.getContext());
            e.setListeners(workerStation.getEventListener(event.getTargetTopic()));
        });
    }
}
